from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
import string
import io

def generate_captcha(length=4, width=120, height=40):
    """生成验证码图片和文本"""
    image = Image.new('RGB', (width, height), (255, 255, 255))
    draw = ImageDraw.Draw(image)
    
    # 生成随机字符
    chars = string.ascii_letters + string.digits
    captcha_text = ''.join(random.choice(chars) for _ in range(length))
    
    # 加载字体
    try:
        font = ImageFont.truetype('arial.ttf', 30)
    except:
        font = ImageFont.load_default()
    
    # 绘制字符
    for i, char in enumerate(captcha_text):
        color = (random.randint(30, 100), random.randint(30, 100), random.randint(30, 100))
        draw.text((30*i + 10, 5), char, font=font, fill=color)
    
    # 绘制干扰线和噪点（省略部分代码，与之前相同）
    for _ in range(3):
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        draw.line(
            [(random.randint(0, width), random.randint(0, height)),
             (random.randint(0, width), random.randint(0, height))],
            fill=color,
            width=2
        )
    
    # 转为字节流
    buf = io.BytesIO()
    image.save(buf, 'png')
    buf.seek(0)
    
    return buf, captcha_text
